package com.hyperfix.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.hyperfix.common.holder.UserHolder;
import com.hyperfix.models.user.dtos.UserDTO;
import com.hyperfix.utils.common.JwtUtil;
import com.hyperfix.utils.common.auth.WhiteURLRegistrar;
import io.jsonwebtoken.Claims;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.lang.NonNull;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.hyperfix.models.constant.common.LoginConstant.LOGIN_USER_PREFIX;

/**
 * @author JiangChunYu
 * 2024/4/15
 */
public class UserInterceptor implements HandlerInterceptor {
    private final StringRedisTemplate stringRedisTemplate;

    public UserInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) {
        String path = request.getRequestURI();
        if (WhiteURLRegistrar.isWhiteURL(path)) {
            return true;
        }
        String token = request.getHeader("token");
        Claims claimsBody = JwtUtil.parseJWT(token);
        String username = claimsBody.getSubject();
        String strUserDTO = stringRedisTemplate.opsForValue().get(LOGIN_USER_PREFIX + username);
        UserDTO userDTO = JSON.parseObject(strUserDTO, UserDTO.class);
        if (userDTO == null) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
        UserHolder.saveUser(userDTO);
        return true;
    }

    @Override
    public void afterCompletion(@NonNull HttpServletRequest request,
                                @NonNull HttpServletResponse response,
                                @NonNull Object handler,
                                Exception ex) {
        UserHolder.removeUser();
    }
}
